import HandleBtn from '@/components/HandleBar/btn';
import type { ActionType, ProColumns } from '@/components/Pro/';
import { ProTable } from '@/components/Pro/';
import {
  factoryDeviceControllerImplDeleteDevice as deleteDevice,
  factoryDeviceControllerImplListDevice as getList,
} from '@/services/ess/factoryDevice';
import { message, Modal, Space } from 'antd';
import React, { useRef, useState } from 'react';
import { useIntl } from 'umi';
const { confirm } = Modal;

const TableList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [disabled, setDisabled] = useState(false);
  const [selectedRows, setSelectedRows] = useState<API.FactoryDevice[]>([]);
  const intl = useIntl();

  // 删除操作
  const handleRemove = async (selectedRows: API.FactoryDevice[]) => {
    if (!selectedRows) return true;
    try {
      const ids = selectedRows.map((row) => row.id);
      const res = await deleteDevice(ids);
      if (res.success) {
        message.success('删除成功');
        return true;
      }
      return false;
    } catch (error) {
      message.error('删除失败');
      return false;
    }
  };

  // 单条记录删除操作
  const handleDelete = async (record: API.FactoryDevice) => {
    if (disabled) return;
    setDisabled(true);

    confirm({
      title: '提示',
      content: '确定要删除该记录吗？',
      onOk: async () => {
        const res = await handleRemove([record]);
        if (res) {
          actionRef.current?.reload();
        }
      },
      afterClose: () => {
        setDisabled(false);
      },
    });
  };

  const columns: ProColumns<API.FactoryDevice>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 80,
      hideInSearch: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createdTime',
      hideInSearch: true,
    },
    {
      title: '设备类型',
      dataIndex: 'deviceType',
      valueType: 'select',
      valueEnum: {
        1: { text: '储能柜' },
        3: { text: 'EMS' },
      },
    },
    {
      title: '出厂编码',
      dataIndex: 'sn',
    },
    {
      title: '绑定状态',
      dataIndex: 'bindStatus',
      valueType: 'select',
      valueEnum: {
        0: { text: '未绑定' },
        1: { text: '已绑定' },
      },
    },
    {
      title: '站点名称',
      dataIndex: 'stationName',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 120,
      render: (_, record) => (
        <Space>
          <a className="global-del-color" onClick={() => handleDelete(record)}>
            删除
          </a>
        </Space>
      ),
    },
  ];

  return (
    <ProTable<API.FactoryDevice>
      headerTitle="出厂设备列表"
      actionRef={actionRef}
      rowKey="id"
      search={{
        labelWidth: 120,
      }}
      request={async (params) => {
        const { current, pageSize, ...rest } = params;
        const res = await getList({
          current,
          pageSize,
          ...rest,
        });
        return {
          data: res.data?.records || [],
          success: res.success,
          total: res.data?.total || 0,
        };
      }}
      columns={columns as ProColumns<API.FactoryDevice>[]}
      rowSelection={{
        onChange: (_, selectedRows) => {
          setSelectedRows(selectedRows);
        },
      }}
      toolBarRender={() => [
        <HandleBtn onClick={() => handleDelete(selectedRows)} handleType="delete" key="delete">
          {intl.formatMessage({ id: 'systemManagement.generalProcedure.batchDelete' })}
        </HandleBtn>,
      ]}
    />
  );
};

export default TableList;
